import time
import json
# import pandas as pd
import requests
import websocket
from requests.adapters import HTTPAdapter
import time
import ssl
import pymongo
import base64
import re
import gzip

try:
    import thread
except ImportError:
    import _thread as thread


def __init__():
    pass


# GZIP解密
def decode_gzip (base64_str):
    res = base64.b64decode(base64_str)
    res = gzip.decompress(res).decode('utf8',"ignore")
    return res

# Base64解密
def decode_base64 (base64_str):
    res = base64.b64decode(base64_str)
    return res

def findNum (key, origin_str):
    res = re.findall('\"' + key + '\":(.*?)(,\"|})', origin_str)
    if len(res) > 0:
        return res
    else:
        return False

def findStr (key, origin_str):
    res = re.findall('\"' + key + '\":\"(.*?)(\",\"|\"})', origin_str)
    if len(res) > 0:
        return res
    else:
        return False


# 这里就是websocket爬虫的核心，发送请求，接收数据并做最后处理，
def on_message(ws, message):
    res_dict = json.loads(message)

    # 判断 data 是否为空
    if res_dict['data'] == '':
        print('data为空')
        return
    print("{} - {}".format(res_dict['compressType'], res_dict['data']))

    if res_dict['compressType'] == 'COMMON':
        res_str = decode_base64(res_dict['data'])
        res_str = res_str.decode("utf8","ignore").strip().replace('\n','').replace('\n', '')
    else:
        res_str = decode_gzip(res_dict['data'])
        res_str = res_str.strip().replace('\n','').replace('\n', '')

    cachedSize = findNum('cachedSize', res_str)
    if cachedSize is not False:
        print('cachedSize：{}'.format(cachedSize[0][0]))

    onlineCount = findNum('onlineCount', res_str)
    if onlineCount is not False:
        print('onlineCount：{}'.format(onlineCount[0][0]))

    pageViewCount = findNum('pageViewCount', res_str)
    if pageViewCount is not False:
        print('pageViewCount：{}'.format(pageViewCount[0][0]))

    serializedSize = findNum('serializedSize', res_str)
    if serializedSize is not False:
        print('serializedSize：{}'.format(serializedSize[0][0]))

    totalCount = findNum('totalCount', res_str)
    if totalCount is not False:
        print('totalCount：{}'.format(totalCount[0][0]))

    nick = findNum('nick', res_str)
    if nick is not False:
        print(nick)
    userid = findNum('userid', res_str)
    if userid is not False:
        print(userid)
    fanLevel = findNum('fanLevel', res_str)
    if fanLevel is not False:
        print(fanLevel)

    print('----------------------------------------------------')


def on_error(ws, error):
    print(error)


# 关闭websocket长连接
def on_close(ws):
    print("关闭连接")

# 程序运行第一步
def on_open(ws):
    def run(*args):
        send_content = {
            # "data": "igkgCAH4AAokZTc0YTFjOGItM2Q2OS00MWM0LWI2YTEtNDhhOWU3Yjg2NWRlEAEiCWg1XzAuNC4xOCqPATUuMCAoTWFjaW50b3NoOyBJbnRlbCBNYWMgT1MgWCAxMF8xNF81KSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNzcuMC4zODY1LjkwIFNhZmFyaS81MzcuMzYgTGliTWVzc2FnZUtpdFNkay8xNTcwNDU5NDAzMzQ2MiQ2NzU3YWE0NC02YzA3LTQ1OGEtYTYxOC1jYjM3NDZhZmQ4MGVCCTcyOTEzMjc3NEoAEAAKDnRiOTEwMDk5NV8yMDExAAA=",
            "data": "igkgCAH4AAokMDA4YjJmODAtNjI4NS00MzRlLWE1MWEtNjFlMmMyMDg0YzMzEAEiCWg1XzAuNC4xOCqPATUuMCAoTWFjaW50b3NoOyBJbnRlbCBNYWMgT1MgWCAxMF8xNF81KSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNzcuMC4zODY1LjkwIFNhZmFyaS81MzcuMzYgTGliTWVzc2FnZUtpdFNkay8xNTcwNTAzNTA0MTc4MiQ5N2RkOWE3NS0zZWNlLTQwNzctODNkZi00MDUxZGQyN2E4YTFCCTcyOTEzMjc3NEoAEAAKDnRiOTEwMDk5NV8yMDExAAA=",
            # "dataId": "59403352_6248",
            "dataId": "3504211_4409",
            "protocol": "ACCS_H5",
            "serviceId": "powermsg",
            "type": "REQ",
        }
        send_content = json.dumps(send_content)
        ws.send(send_content)
        print("thread terminating...")
    thread.start_new_thread(run, ())


if __name__ == "__main__":

    myclient = pymongo.MongoClient("mongodb://47.98.146.210:27017")
    mydb_cookies = myclient["QK_GOODS"]
    mycol_cookies = mydb_cookies['qk_cookies']
    cookiee = mycol_cookies.find({}).sort([('_id', -1)]).limit(1)
    for cook in cookiee:
        qk_1688 = cook['qk_1688']

    header = {
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,',
        'Cache-Control': 'no-cache',
        'Connection': 'Upgrade',
        'Cookie': qk_1688,
        'Host': 'acs.m.taobao.com:80',
        'Origin': 'https://taobaolive.taobao.com',
        'Pragma': 'no-cache',
        'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
        # 这个参数要进行实时修改
        'Sec-WebSocket-Key': 'WV9B4PXjzHvsFOaK4Vuzzg==',
        'Sec-WebSocket-Version': '13',
        'Upgrade': 'websocket',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
    }

    websocket.enableTrace(True)
    # websocket_obj = websocket_class()
    url = "wss://acs.m.taobao.com:80/accs/auth?token=AAABXZw762H+MWPJqJSaTphUfE1e7/zIxiPOfL/oMxlMxGWYPvFgf49I5c86TizwP94An3tsIeY9nu2V7opLOiXjsOT+OJY="
    print(url)
    ws = websocket.WebSocketApp(url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close,
                                header=header)

    ws.on_open = on_open
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})